package com.sinochem.yunlian.ship.base.method;

import com.sinochem.yunlian.ship.base.biz.RpcCommonBiz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.sinochem.yunlian.ship.api.vo.uc.UcUserInfo;
import com.sinochem.yunlian.ship.base.feign.IUserService;
import com.sinochem.yunlian.ship.common.annotation.Subject;
import com.sinochem.yunlian.ship.common.enums.ResponseCode;
import com.sinochem.yunlian.ship.common.exception.BaseException;

public class SubjectMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private IUserService iUserService;
    @Autowired
    private RpcCommonBiz rpcCommonBiz;
    
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Subject.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory) throws Exception {
        Subject annoSubject = parameter.getParameterAnnotation(Subject.class);
        try {
            //sso的用户id
            String userId = webRequest.getHeader("currentUserId");
            LOG.info("currentUserId:{}",userId);
            UcUserInfo currentUser = rpcCommonBiz.getSubject(userId);
            
            if (currentUser == null) {
                throw new BaseException(ResponseCode.NO_PERMISSION.getName(),ResponseCode.NO_PERMISSION.getCode());
            }
            if (currentUser.getCompanyId() == null && annoSubject.required() == true) {
                throw new BaseException(currentUser.getMessage(),currentUser.getCode());
            }
            return currentUser;
        } catch (Exception e) {
            throw new Exception("无效的用户");
        }
    }

}